package xyz.poke.business.tool.utils;

import org.apache.commons.lang3.BooleanUtils;
import org.springframework.util.CollectionUtils;
import xyz.poke.business.tool.dto.TreeDTO;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 迫壳
 * @date 2024/3/19 20:44
 */
public class TreeUtils {

    public static void main(String[] args) {
        List<TreeDTO.NodeDTO> nodeList = new ArrayList<>();
        TreeDTO.NodeDTO node = new TreeDTO.NodeDTO("1", "node01", null, false);
        nodeList.add(node);
        node = new TreeDTO.NodeDTO("2", "node02", null, false);
        nodeList.add(node);
        node = new TreeDTO.NodeDTO("1-1", "node03", "1", false);
        nodeList.add(node);
        node = new TreeDTO.NodeDTO("1-1-1", "node04", "1-1", false);
        nodeList.add(node);
        TreeDTO treeDTO = TreeUtils.initTree(nodeList);
        System.out.println(treeDTO);
    }

    public static TreeDTO initTree(List<TreeDTO.NodeDTO> nodeList) {
        TreeDTO root = new TreeDTO();
        if (CollectionUtils.isEmpty(nodeList)) {
            return root;
        }
        List<TreeDTO.NodeDTO> sortedNodes = nodeList.stream().sorted((o1, o2) -> {
            if (Objects.isNull(o1.getFatherCode())) {
                return -1;
            }
            if (Objects.isNull(o2.getFatherCode())) {
                return 1;
            }
            return o1.getFatherCode().compareTo(o2.getFatherCode());
        }).collect(Collectors.toList());
        initTree(sortedNodes, 0, root);
        return root;
    }

    private static void initTree(List<TreeDTO.NodeDTO> nodeList, int start, TreeDTO root) {
        if (start >= nodeList.size()) {
            return ;
        }
        for (int i = start; i < nodeList.size(); i++) {
            TreeDTO.NodeDTO node = nodeList.get(i);
            if (Objects.equals(node.getFatherCode(), root.getCurrentNode().getCode()) && BooleanUtils.isFalse(node.getSelected())) {
                TreeDTO childTree = new TreeDTO();
                childTree.setCurrentNode(node);
                node.setSelected(true);
                initTree(nodeList, i+1, childTree);
                root.getChildren().add(childTree);
            }
        }
    }

}
